package com.xiaoma.bingo.web;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.xiaoma.bingo.dto.LoginDto;
import com.xiaoma.bingo.entity.User;
import com.xiaoma.bingo.service.UserService;
import com.xiaoma.bingo.utils.Bingo;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    
    @RequestMapping(value="/login", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject login(LoginDto loginDto, HttpSession session) {
        User user = userService.findByNameAndPwd(loginDto.getUserName(), loginDto.getPassword());
        JSONObject result = new JSONObject();
        if(null != user) {
            session.setAttribute(Bingo.CURRENT_USER, user);
            result.put("status", 1);
        } else {
            result.put("status", 0);
            result.put("message", "用户名或密码不正确");
        }
        return result;
    }
    
    @RequestMapping(value="/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }
    
    @RequestMapping(value="/app/main", method = RequestMethod.GET)
    public String main(HttpSession session, Model model) {
        return "main";
    }
    
    @RequestMapping(value="/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        session.removeAttribute(Bingo.CURRENT_USER);
        return "redirect:/login";
    }
}
